package models

import "github.com/astaxie/beego/orm"

type AiNumbers struct {
	Id         int64
	Dst_number string
	Num_own    string
}

func (a *AiNumbers) TableName() string {
	return TableName("numbers")
}

func AiNumbersAdd(a *AiNumbers) (int64, error) {
	return orm.NewOrm().InsertOrUpdate(a, "dst_number", "id=id+1")
}

func AiNumbersGetByName(dstNumber string) (*AiNumbers, error) {
	a := new(AiNumbers)
	err := orm.NewOrm().QueryTable(TableName("numbers")).Filter("dst_number", dstNumber).One(a)
	if err != nil {
		return nil, err
	}
	return a, nil
}

func AiNumbersGetList(page, pageSize int, filters ...interface{}) ([]*AiNumbers, int64) {
	offset := (page - 1) * pageSize
	list := make([]*AiNumbers, 0)
	query := orm.NewOrm().QueryTable(TableName("numbers"))
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy("-id").Limit(pageSize, offset).All(&list)

	return list, total
}

func AiNumbersGetById(id int) (*AiNumbers, error) {
	r := new(AiNumbers)
	err := orm.NewOrm().QueryTable(TableName("numbers")).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

func (a *AiNumbers) Update(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}

func (a *AiNumbers) Delete() error {
	if _, err := orm.NewOrm().Delete(a); err != nil {
		return err
	}
	return nil
}
func (a *AiNumbers) DeleteMap() error {
	if _, err := orm.NewOrm().Delete(a); err != nil {
		return err
	}
	return nil
}

func (a *AiNumbers) CheckNumber(num string) (int64, error) {

	n := new(AiNumbers)
	err := orm.NewOrm().QueryTable(TableName("numbers")).Filter("dst_number", num).One(n)
	if err != nil {
		return 0, err
	}
	return n.Id, nil
}
